document.addEventListener("DOMContentLoaded", function() {
    fetchUserInfo();
});

let currentUserId;
let currentUsername;
let currentAvatarUrl;
let receiveUserId;

function fetchUserInfo() {
    fetch('http://101.34.242.206:9990/users/queryCurrentUserInfo')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.code === 200) {
                currentUserId = data.data.id;
                currentUsername = data.data.nickname;
                currentAvatarUrl = data.data.headerurl;

                document.getElementById('header-nickname').textContent = currentUsername;
                document.getElementById('header-avatar').src = currentAvatarUrl;

                initWebSocket(currentUserId, currentUsername, currentAvatarUrl);
            } else {
                alert('您还未登录！');
            }
        })
        .catch(error => {
            console.error('Error fetching user data:', error);
            alert('您还未登录！');
        });
}

function initWebSocket(userId, username, avatarUrl) {
    const messageInput = document.getElementById('message-input');
    const chatBox = document.getElementById('chat-box');

    const ws = new WebSocket(`ws://101.34.242.206:9990/websocket/${userId}`);

    ws.onopen = function() {
        console.log('WebSocket连接已打开');
    };

    ws.onmessage = function(event) {
        try {
            const message = event.data;
            console.log("接收到的消息：", message);  // 调试信息
            const parsedMessage = JSON.parse(message);
            console.log("解析后的消息：", parsedMessage);
            if (parsedMessage && parsedMessage.headerUrl && parsedMessage.name && parsedMessage.content) {
                displayMessage(parsedMessage);
            } else {
                console.error("消息对象不完整：", parsedMessage);
            }
        } catch (e) {
            console.error("解析消息时出错：", e, event.data);
        }
    };

    ws.onclose = function() {
        console.log('WebSocket连接已关闭');
    };

    ws.onerror = function(error) {
        console.log('WebSocket发生错误: ' + error.message);
    };

    window.sendMessage = function() {
        const messageText = messageInput.value.trim();

        if (messageText !== "") {
            const message = {
                content: messageText,
                receiveUserId: receiveUserId,
                messageType: 'single',
                headerUrl: avatarUrl,
                name: username
            };

            const messageString = JSON.stringify(message);
            console.log("发送的消息：", messageString);  // 调试信息
            ws.send(messageString);

            displayMessage({
                headerUrl: avatarUrl,
                name: username,
                content: messageText
            });

            messageInput.value = "";
        }
    };

    function displayMessage(message) {
        const chatBox = document.getElementById('chat-box');
        const messageElement = document.createElement('div');
        messageElement.classList.add('chat-message');

        // 处理消息内容，将带引号的整个消息转换为超链接
        const messageText = message.content || message.message;
        const quoteRegex = /"([^"]*?\((https?:\/\/[^\s()]+)\))"/g;
        let messageContent = messageText;

        messageContent = messageContent.replace(quoteRegex, (match, p1, p2) => {
            return `<a href="${p2}" target="_blank">${p1}</a>`;
        });

        messageElement.innerHTML = `
        <img src="${message.headerUrl}" alt="头像" class="avatar">
        <div class="message ${message.name === currentUsername ? 'user' : 'bot'}">
            <span class="message-name">${message.name}</span>${messageContent}
        </div>
    `;
        chatBox.appendChild(messageElement);
        chatBox.scrollTop = chatBox.scrollHeight;
    }




    messageInput.addEventListener('keypress', function(event) {
        if (event.key === 'Enter') {
            sendMessage();
        }
    });
}

function searchUser() {
    const searchInput = document.getElementById('search-input').value.trim();

    if (searchInput !== "") {
        fetch(`http://101.34.242.206:9998/webSocket/getUserByName?name=${searchInput}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.data) {
                    const user = data.data;
                    displaySearchResult(user);
                } else {
                    alert('未找到用户');
                }
            })
            .catch(error => {
                console.error('Error fetching user data:', error);
                alert('未找到用户');
            });
    }
}

function displaySearchResult(user) {
    const userList = document.getElementById('user-list');
    userList.innerHTML = ''; // 清空之前的搜索结果

    const userItem = document.createElement('div');
    userItem.classList.add('user-item');
    userItem.innerHTML = `
        <img src="${user.headerurl}" alt="头像" class="avatar">
        <div>
            <span class="user-name">${user.nickname}</span>
        </div>
    `;
    userItem.onclick = function() {
        receiveUserId = user.id;
        loadChatHistory(currentUserId, receiveUserId);
    };
    userList.appendChild(userItem);
}

function loadChatHistory(fromUserId, receiveUserId) {
    fetch(`http://101.34.242.206:9990/webSocket/getSingleMessage?fromUserId=${fromUserId}&receiveUserId=${receiveUserId}&pageNum=1&pageSize=20`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                const messages = data.data;
                const chatBox = document.getElementById('chat-box');
                chatBox.innerHTML = ''; // 清空之前的聊天记录
                messages.forEach(message => {
                    displayMessage({
                        headerUrl: message.headerUrl,
                        name: message.name,
                        content: message.message
                    });
                });
            } else {
                console.error('Error loading chat history:', data.message);
            }
        })
        .catch(error => console.error('Error loading chat history:', error));
}

function displayMessage(message) {
    const chatBox = document.getElementById('chat-box');
    const messageElement = document.createElement('div');
    messageElement.classList.add('chat-message');
    messageElement.innerHTML = `
        <img src="${message.headerUrl}" alt="头像" class="avatar">
        <div class="message ${message.name === currentUsername ? 'user' : 'bot'}">
            <span class="message-name">${message.name}</span>${message.content}
        </div>
    `;
    chatBox.appendChild(messageElement);
    chatBox.scrollTop = chatBox.scrollHeight;
}




